package umlms.server.service;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;

public class UMLMSServer implements Runnable {

	private int port = 9999;
	private boolean isRunning = false;

	private List<RequestListener> requestListenerList = new ArrayList<RequestListener>();

	public void addRequestListener(RequestListener listener) {
		requestListenerList.add(listener);
	}

	public void removeRequestListener(RequestListener listener) {
		requestListenerList.remove(listener);
	}

	public void initialize(Settings settings) {
	}

	public void stop() {
		isRunning = false;
	}

	public void run() {

		isRunning = true;

		do {

			DatagramSocket socket;
			try {
				socket = new DatagramSocket(port);
			} catch (SocketException e) {
				throw new RuntimeException(e);
			}

			byte[] buffer = new byte[128];

			DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
			try {
				socket.receive(packet);
			} catch (IOException e) {
				throw new RuntimeException(e);
			}

			int packetLen = packet.getLength();
			int offSet = packet.getOffset();
			byte[] packetContents = new byte[packetLen];
			System.arraycopy(buffer, offSet, packetContents, 0, packetLen);

			String request = new String(packetContents);
			String response = null;
			for (RequestListener listener : requestListenerList) {

				String listenerResponse = listener.requestRecieved(request);
				if ((null == response) && (null != listenerResponse)) {
					response = listenerResponse;
				}
			}

			buffer = response.getBytes();

			InetAddress address = packet.getAddress();
			int port = packet.getPort();

			packet = new DatagramPacket(buffer, buffer.length);
			packet.setAddress(address);
			packet.setPort(port);

			System.out.println("Sending: " + response + " to: " + address
					+ " : " + port);

			try {
				socket.send(packet);
				socket.close();
			} catch (IOException e) {
				throw new RuntimeException(e);
			}

		} while (isRunning);
	}
}
